package com.googlecode.fcgi4j.message;

import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

import com.googlecode.fcgi4j.FCGIException;
import com.googlecode.fcgi4j.constant.FCGIHeaderType;

/**
 *
 * @author panzd
 */
public class FCGIParams {
    public static final FCGIParams NULL = new FCGIParams();
	private Map<String, String> params;

    public FCGIParams() {
    }
    
    public void addParams(String key, String value)
    {
    	if(key == null || value == null){
            throw new FCGIException("FCGI_RARAMS's key and value can't be null");
        }
    	
    	if(params == null)
    	{
    		params = new HashMap<String, String>();
    	}
    	
    	params.put(key, value);
    }
    
    public void clear()
    {
    	params = null;
    }
    
    public ByteBuffer[] getByteBuffers() {
    	ByteBuffer[] buffers;
    	if(params == null)
    	{
    		FCGIHeader header = new FCGIHeader(FCGIHeaderType.FCGI_PARAMS, 0);
    		
    		buffers = new ByteBuffer[]{header.getByteBuffer()};
    	}
    	else
    	{
            buffers = new ByteBuffer[params.size() + 1];

            int length = 0;
    		int index = 1;
    		
    		for(String key : params.keySet())
    		{
    			FCGINameValuePair pair = new FCGINameValuePair(key, params.get(key));

    			buffers[index] = pair.getByteBuffer();

    			length += pair.getLength();
    			++ index;
    		}

        	FCGIHeader header = new FCGIHeader(FCGIHeaderType.FCGI_PARAMS, length);
            buffers[0] = header.getByteBuffer();
    	}

        return buffers;
    }
}
